<template>
  <div class="parking-lot-management">
    <div class="page-header">
      <h1>停车场管理</h1>
      <p>管理系统中的所有停车场信息</p>
    </div>

    <!-- 操作区域 -->
    <div class="operation-bar">
      <div class="search-area">
        <el-input v-model="searchForm.name" placeholder="请输入停车场名称搜索" style="width: 300px" clearable
          @keyup.enter="handleSearch" @clear="handleSearch">
          <template #prefix>
            <el-icon>
              <Search />
            </el-icon>
          </template>
        </el-input>

        <el-select v-model="searchForm.status" placeholder="选择状态" style="width: 150px; margin-left: 10px" clearable
          @change="handleSearch">
          <el-option label="待审核" value="pending_review" />
          <el-option label="已通过" value="approved" />
          <el-option label="已拒绝" value="rejected" />
          <el-option label="已停用" value="inactive" />
        </el-select>

        <el-button type="primary" @click="handleSearch" :loading="loading">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </el-button>
      </div>

      <div class="action-area">
        <el-button type="primary" @click="handleAdd">
          <el-icon>
            <Plus />
          </el-icon>
          新增停车场
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table :data="tableData" :loading="loading" stripe style="width: 100%" @sort-change="handleSortChange">
        <el-table-column prop="id" label="ID" width="80" sortable />

        <el-table-column prop="name" label="停车场名称" min-width="150" show-overflow-tooltip />

        <el-table-column prop="category_name" label="分类" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.category_name" size="small">{{ row.category_name }}</el-tag>
            <span v-else class="text-gray">未分类</span>
          </template>
        </el-table-column>

        <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip />

        <el-table-column prop="total_spaces" label="车位数" width="100" align="center">
          <template #default="{ row }">
            <span>{{ row.total_spaces || 0 }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="monthly_sales" label="月销量" width="100" align="center">
          <template #default="{ row }">
            <span>{{ row.monthly_sales || 0 }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="rating" label="评分" width="100" align="center">
          <template #default="{ row }">
            <el-rate v-model="row.rating" disabled size="small" show-score />
          </template>
        </el-table-column>

        <el-table-column label="距离信息" width="150" align="center">
          <template #default="{ row }">
            <div class="distance-info">
              <div v-if="row.airport_distance_km" class="distance-item">
                <span class="distance-label">机场:</span>
                <span class="distance-value">{{ row.airport_distance_km }}km</span>
              </div>
              <div v-if="row.station_distance_km" class="distance-item">
                <span class="distance-label">高铁:</span>
                <span class="distance-value">{{ row.station_distance_km }}km</span>
              </div>
              <div v-if="row.shuttle_time_minutes" class="distance-item">
                <span class="distance-label">摆渡:</span>
                <span class="distance-value">{{ row.shuttle_time_minutes }}分钟</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="created_at" label="创建时间" width="180" sortable>
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="360" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon>
                <Edit />
              </el-icon>
              编辑
            </el-button>
            <el-button type="info" size="small" @click="handleViewReviews(row)">
              <el-icon>
                <ChatDotRound />
              </el-icon>
              评价
            </el-button>
            <el-button type="success" size="small" @click="handleAddReview(row)">
              <el-icon>
                <Plus />
              </el-icon>
              添加评论
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon>
                <Delete />
              </el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="900px" :close-on-click-modal="false"
      @close="handleDialogClose">
      <el-tabs v-model="activeTab" type="border-card">
        <!-- 基础信息标签页 -->
        <el-tab-pane label="基础信息" name="basic">
          <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" @submit.prevent>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="停车场名称" prop="name">
                  <el-input v-model="formData.name" placeholder="请输入停车场名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="分类" prop="category_id">
                  <el-select v-model="formData.category_id" placeholder="请选择分类" style="width: 100%">
                    <el-option v-for="category in categories" :key="category.id" :label="category.name"
                      :value="category.id" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="详细地址" prop="address">
              <el-input v-model="formData.address" placeholder="请输入详细地址" />
            </el-form-item>



            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="车位数量" prop="total_spaces">
                  <el-input-number v-model="formData.total_spaces" :min="0" :max="9999" style="width: 100%"
                    placeholder="请输入车位数量" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="月销量" prop="monthly_sales">
                  <el-input-number v-model="formData.monthly_sales" :min="0" :max="9999" style="width: 100%"
                    placeholder="请输入月销量" />
                  <div class="field-tip">系统会自动统计，也可手动设置</div>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="评分" prop="rating">
                  <el-input-number v-model="formData.rating" :min="0" :max="5" :precision="2" :step="0.1"
                    style="width: 100%" placeholder="请输入评分" />
                  <div class="field-tip">0-5分，系统会根据用户评价自动更新</div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="距机场距离" prop="airport_distance_km">
                  <el-input-number v-model="formData.airport_distance_km" :min="0" :max="999" :precision="1" :step="0.5"
                    style="width: 100%" placeholder="请输入距机场距离" />
                  <div class="field-tip">单位：公里，可选填</div>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="距高铁站距离" prop="station_distance_km">
                  <el-input-number v-model="formData.station_distance_km" :min="0" :max="999" :precision="1" :step="0.5"
                    style="width: 100%" placeholder="请输入距高铁站距离" />
                  <div class="field-tip">单位：公里，可选填</div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="摆渡车时间" prop="shuttle_time_minutes">
                  <el-input-number v-model="formData.shuttle_time_minutes" :min="0" :max="999" style="width: 100%"
                    placeholder="请输入摆渡车时间" />
                  <div class="field-tip">单位：分钟，可选填</div>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="联系电话" prop="contact_phone">
                  <el-input v-model="formData.contact_phone" placeholder="请输入联系电话" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="备用电话" prop="backup_phone">
                  <el-input v-model="formData.backup_phone" placeholder="请输入备用联系电话" />
                  <div class="field-tip">可选填</div>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item v-if="isEdit" label="状态" prop="status">
              <el-select v-model="formData.status" style="width: 200px">
                <el-option label="待审核" value="pending_review" />
                <el-option label="已通过" value="approved" />
                <el-option label="已拒绝" value="rejected" />
                <el-option label="已停用" value="inactive" />
              </el-select>
            </el-form-item>

            <!-- 价格规则配置 -->
            <el-form-item label="价格规则">
              <div class="price-rules-container">
                <div class="price-rules-header">
                  <span class="rules-title">停车价格规则设置</span>
                  <div class="header-actions">
                    <el-radio-group v-model="pricingConfig.type" size="small" style="margin-right: 16px">
                      <el-radio-button label="cumulative_daily">自然天计费</el-radio-button>
                      <el-radio-button label="rolling_24h">24小时计费</el-radio-button>
                    </el-radio-group>
                    <el-switch
                      v-model="pricingConfig.indoor_outdoor_enabled"
                      active-text="启用室内外分别定价"
                      inactive-text="统一定价"
                      style="margin-right: 16px"
                      @change="onIndoorOutdoorToggle"
                    />
                    <el-button type="info" size="small" @click="resetToDefaultPricing">
                      <el-icon>
                        <Refresh />
                      </el-icon>
                      重置为默认
                    </el-button>
                  </div>
                </div>

                <div class="pricing-config">
                  <!-- 统一定价模式 -->
                  <div v-if="!pricingConfig.indoor_outdoor_enabled" class="unified-pricing">
                    <!-- 1-7天累计价格配置 -->
                    <div class="daily-prices-section">
                      <h4 class="section-title">1-7天累计价格配置</h4>
                      <div class="daily-prices-grid">
                        <div class="daily-price-item">
                          <el-form-item label="第1天累计" prop="pricingConfig.daily_prices.day_1">
                            <div class="price-input-wrapper">
                              <input 
                                type="number" 
                                v-model.number="pricingConfig.daily_prices.day_1" 
                                min="0" 
                                max="9999" 
                                step="0.01" 
                                placeholder="第1天累计费用"
                                class="el-input-style" />
                              <span class="price-unit">元</span>
                            </div>
                          </el-form-item>
                        </div>
                        <div class="daily-price-item">
                          <el-form-item label="第2天累计" prop="pricingConfig.daily_prices.day_2">
                            <div class="price-input-wrapper">
                              <input 
                                type="number" 
                                v-model.number="pricingConfig.daily_prices.day_2" 
                                min="0" 
                                max="9999" 
                                step="0.01" 
                                placeholder="第2天累计费用"
                                class="el-input-style" />
                              <span class="price-unit">元</span>
                            </div>
                          </el-form-item>
                        </div>
                        <div class="daily-price-item">
                          <el-form-item label="第3天累计" prop="pricingConfig.daily_prices.day_3">
                            <div class="price-input-wrapper">
                              <input 
                                type="number" 
                                v-model.number="pricingConfig.daily_prices.day_3" 
                                min="0" 
                                max="9999" 
                                step="0.01" 
                                placeholder="第3天累计费用"
                                class="el-input-style" />
                              <span class="price-unit">元</span>
                            </div>
                          </el-form-item>
                        </div>
                        <div class="daily-price-item">
                          <el-form-item label="第4天累计" prop="pricingConfig.daily_prices.day_4">
                            <div class="price-input-wrapper">
                              <input 
                                type="number" 
                                v-model.number="pricingConfig.daily_prices.day_4" 
                                min="0" 
                                max="9999" 
                                step="0.01" 
                                placeholder="第4天累计费用"
                                class="el-input-style" />
                              <span class="price-unit">元</span>
                            </div>
                          </el-form-item>
                        </div>
                        <div class="daily-price-item">
                          <el-form-item label="第5天累计" prop="pricingConfig.daily_prices.day_5">
                            <div class="price-input-wrapper">
                              <input 
                                type="number" 
                                v-model.number="pricingConfig.daily_prices.day_5" 
                                min="0" 
                                max="9999" 
                                step="0.01" 
                                placeholder="第5天累计费用"
                                class="el-input-style" />
                              <span class="price-unit">元</span>
                            </div>
                          </el-form-item>
                        </div>
                        <div class="daily-price-item">
                          <el-form-item label="第6天累计" prop="pricingConfig.daily_prices.day_6">
                            <div class="price-input-wrapper">
                              <input 
                                type="number" 
                                v-model.number="pricingConfig.daily_prices.day_6" 
                                min="0" 
                                max="9999" 
                                step="0.01" 
                                placeholder="第6天累计费用"
                                class="el-input-style" />
                              <span class="price-unit">元</span>
                            </div>
                          </el-form-item>
                        </div>
                        <div class="daily-price-item">
                          <el-form-item label="第7天累计" prop="pricingConfig.daily_prices.day_7">
                            <div class="price-input-wrapper">
                              <input 
                                type="number" 
                                v-model.number="pricingConfig.daily_prices.day_7" 
                                min="0" 
                                max="9999" 
                                step="0.01" 
                                placeholder="第7天累计费用"
                                class="el-input-style" />
                              <span class="price-unit">元</span>
                            </div>
                          </el-form-item>
                        </div>
                      </div>
                    </div>

                    <!-- 第8天起每日价格 -->
                    <div class="after-7-days-section">
                      <h4 class="section-title">第8天起每日价格</h4>
                      <el-form-item label="每日价格" prop="pricingConfig.daily_price_after_7">
                        <div class="price-input-wrapper">
                          <input 
                            type="number" 
                            v-model.number="pricingConfig.daily_price_after_7" 
                            min="0" 
                            max="999" 
                            step="0.01" 
                            placeholder="第8天起每日价格"
                            class="el-input-style"
                            style="width: 200px" />
                          <span class="price-unit">元/天</span>
                        </div>
                      </el-form-item>
                    </div>
                  </div>

                  <!-- 室内外分别定价模式 -->
                  <div v-else class="indoor-outdoor-pricing">
                    <el-alert
                      title="室内外分别定价模式"
                      type="info"
                      :closable="false"
                      show-icon
                      style="margin-bottom: 20px"
                    >
                      <template #default>
                        启用后，用户在预订时可以选择室内或室外停车位，系统将根据选择的类型计算相应价格。
                        <strong>注意：未启用时默认按室内价格计算。</strong>
                      </template>
                    </el-alert>

                    <!-- 室内价格配置 -->
                    <div class="indoor-pricing-section">
                      <h4 class="section-title">🏠 室内停车价格配置</h4>
                      <div class="daily-prices-grid">
                        <div v-for="day in 7" :key="`indoor-${day}`" class="daily-price-item">
                          <el-form-item :label="`第${day}天累计`">
                            <el-input-number v-model="pricingConfig.indoor_prices.daily_prices[`day_${day}`]" :min="0" :max="9999"
                              :precision="2" :step="10" style="width: 100%" :placeholder="`第${day}天累计费用`" />
                            <span class="price-unit">元</span>
                          </el-form-item>
                        </div>
                      </div>
                      <div class="after-7-days-section">
                        <el-form-item label="第8天起每日价格">
                          <el-input-number v-model="pricingConfig.indoor_prices.daily_price_after_7" :min="0" :max="999" :precision="2"
                            :step="5" style="width: 200px" placeholder="第8天起每日价格" />
                          <span class="price-unit">元/天</span>
                        </el-form-item>
                      </div>
                    </div>

                    <!-- 室外价格配置 -->
                    <div class="outdoor-pricing-section">
                      <h4 class="section-title">🌤️ 室外停车价格配置</h4>
                      <div class="daily-prices-grid">
                        <div v-for="day in 7" :key="`outdoor-${day}`" class="daily-price-item">
                          <el-form-item :label="`第${day}天累计`">
                            <el-input-number v-model="pricingConfig.outdoor_prices.daily_prices[`day_${day}`]" :min="0" :max="9999"
                              :precision="2" :step="10" style="width: 100%" :placeholder="`第${day}天累计费用`" />
                            <span class="price-unit">元</span>
                          </el-form-item>
                        </div>
                      </div>
                      <div class="after-7-days-section">
                        <el-form-item label="第8天起每日价格">
                          <el-input-number v-model="pricingConfig.outdoor_prices.daily_price_after_7" :min="0" :max="999" :precision="2"
                            :step="5" style="width: 200px" placeholder="第8天起每日价格" />
                          <span class="price-unit">元/天</span>
                        </el-form-item>
                      </div>
                    </div>
                  </div>

                  <!-- 价格预览 -->
                  <div class="price-preview-section">
                    <h4 class="section-title">价格预览</h4>

                    <!-- 统一定价预览 -->
                    <div v-if="!pricingConfig.indoor_outdoor_enabled" class="preview-grid">
                      <div v-for="day in 10" :key="day" class="preview-item">
                        <span class="preview-day">第{{ day }}天</span>
                        <span class="preview-price">{{ getPreviewPrice(day) }}元</span>
                      </div>
                    </div>

                    <!-- 室内外分别定价预览 -->
                    <div v-else class="indoor-outdoor-preview">
                      <div class="indoor-preview">
                        <h5 class="preview-subtitle">🏠 室内停车价格预览</h5>
                        <div class="preview-grid">
                          <div v-for="day in 10" :key="`indoor-preview-${day}`" class="preview-item">
                            <span class="preview-day">第{{ day }}天</span>
                            <span class="preview-price">{{ getIndoorPreviewPrice(day) }}元</span>
                          </div>
                        </div>
                      </div>

                      <div class="outdoor-preview">
                        <h5 class="preview-subtitle">🌤️ 室外停车价格预览</h5>
                        <div class="preview-grid">
                          <div v-for="day in 10" :key="`outdoor-preview-${day}`" class="preview-item">
                            <span class="preview-day">第{{ day }}天</span>
                            <span class="preview-price">{{ getOutdoorPreviewPrice(day) }}元</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- 价格说明 -->
                  <div class="pricing-description">
                    <el-alert title="价格规则说明" type="info" :closable="false" show-icon>
                      <template #default>
                        <ul>
                          <li>
                            计费模式：
                            <strong v-if="pricingConfig.type==='rolling_24h'">24小时计费</strong>
                            <strong v-else>自然天计费</strong>
                            ，均为不足一整天按一整天计费。
                          </li>
                          <li>自然天计费，一个日期为一天（如：5.2-5.5为4个自然天）</li>
                          <li v-if="!pricingConfig.indoor_outdoor_enabled">1-7天使用累计价格，例如停车3天收费{{ pricingConfig.daily_prices.day_3 }}元</li>
                          <li v-if="!pricingConfig.indoor_outdoor_enabled">第8天起每天额外收费{{ pricingConfig.daily_price_after_7 }}元</li>
                          <li v-if="!pricingConfig.indoor_outdoor_enabled">例如停车10天：前7天{{ pricingConfig.daily_prices.day_7 }}元 + 后3天{{
                            pricingConfig.daily_price_after_7 * 3 }}元 = {{ pricingConfig.daily_prices.day_7 +
                              pricingConfig.daily_price_after_7 * 3 }}元</li>
                          <li v-if="pricingConfig.indoor_outdoor_enabled">
                            <strong>室内外分别定价：</strong>用户可选择室内或室外停车位，系统按选择类型计算价格
                          </li>
                          <li v-if="pricingConfig.indoor_outdoor_enabled">
                            <strong>默认类型：</strong>未启用分别定价时，默认按室内价格计算
                          </li>
                          <li>价格配置后立即生效，影响新订单的价格计算</li>
                        </ul>
                      </template>
                    </el-alert>
                  </div>
                </div>
              </div>
            </el-form-item>

            <!-- 营业资料上传 -->
            <el-form-item label="营业资料">
              <div class="business-documents-container">
                <div class="document-section">
                  <h4 class="document-title">营业执照</h4>
                  <el-upload v-model:file-list="businessLicenseFileList" :action="API_CONFIG.UPLOAD_IMAGE_URL"
                    list-type="picture-card" :headers="uploadHeaders"
                    :on-success="(response, file) => handleBusinessDocumentUploadSuccess(response, file, 'business_license')"
                    :on-error="handleBusinessDocumentUploadError"
                    :on-remove="(file) => handleBusinessDocumentRemove(file, 'business_license')"
                    :before-upload="beforeBusinessDocumentUpload" :limit="1" accept="image/*,.pdf">
                    <el-icon>
                      <Plus />
                    </el-icon>
                    <template #tip>
                      <div class="el-upload__tip">
                        支持 jpg/png/pdf 格式，单个文件不超过 5MB
                      </div>
                    </template>
                  </el-upload>
                </div>

                <div class="document-section">
                  <h4 class="document-title">法人身份证</h4>
                  <el-upload v-model:file-list="legalIdFileList" :action="API_CONFIG.UPLOAD_IMAGE_URL"
                    list-type="picture-card" :headers="uploadHeaders"
                    :on-success="(response, file) => handleBusinessDocumentUploadSuccess(response, file, 'legal_id')"
                    :on-error="handleBusinessDocumentUploadError"
                    :on-remove="(file) => handleBusinessDocumentRemove(file, 'legal_id')"
                    :before-upload="beforeBusinessDocumentUpload" :limit="2" accept="image/*,.pdf">
                    <el-icon>
                      <Plus />
                    </el-icon>
                    <template #tip>
                      <div class="el-upload__tip">
                        支持 jpg/png/pdf 格式，最多上传2张（正反面）
                      </div>
                    </template>
                  </el-upload>
                </div>

                <div class="document-section">
                  <h4 class="document-title">场地租赁合同</h4>
                  <el-upload v-model:file-list="leaseContractFileList" :action="API_CONFIG.UPLOAD_IMAGE_URL"
                    list-type="picture-card" :headers="uploadHeaders"
                    :on-success="(response, file) => handleBusinessDocumentUploadSuccess(response, file, 'lease_contract')"
                    :on-error="handleBusinessDocumentUploadError"
                    :on-remove="(file) => handleBusinessDocumentRemove(file, 'lease_contract')"
                    :before-upload="beforeBusinessDocumentUpload" :limit="3" accept="image/*,.pdf">
                    <el-icon>
                      <Plus />
                    </el-icon>
                    <template #tip>
                      <div class="el-upload__tip">
                        支持 jpg/png/pdf 格式，最多上传3个文件
                      </div>
                    </template>
                  </el-upload>
                </div>
              </div>
            </el-form-item>

            <!-- 服务设施复选框 -->
            <el-form-item label="服务设施">
              <el-checkbox-group v-model="serviceFacilitiesList" class="facilities-group">
                <el-checkbox label="has_charging_pile">有充电桩</el-checkbox>
                <el-checkbox label="is_24_hours">24小时开放</el-checkbox>
                <el-checkbox label="has_camera">有监控摄像头</el-checkbox>
                <el-checkbox label="is_indoor">室内停车场</el-checkbox>
                <el-checkbox label="has_24h_shuttle">24H免费接送</el-checkbox>
                <el-checkbox label="has_staff_on_duty">专人值守</el-checkbox>
                <el-checkbox label="has_surveillance">摄像监控</el-checkbox>
                <el-checkbox label="has_7_seat_shuttle">7座车接送</el-checkbox>
                <el-checkbox label="has_5_seat_shuttle">5座车接送</el-checkbox>
                <el-checkbox label="has_parking_invoice">停车场发票</el-checkbox>
                <el-checkbox label="walking_distance">步行即达</el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <!-- 停车场图片上传 -->
            <el-form-item label="停车场图片">
              <el-upload v-model:file-list="imageFileList" :action="API_CONFIG.UPLOAD_IMAGE_URL"
                list-type="picture-card" :headers="uploadHeaders" :on-success="handleImageUploadSuccess"
                :on-error="handleImageUploadError" :on-remove="handleImageRemove" :before-upload="beforeImageUpload"
                multiple :limit="6" accept="image/*">
                <el-icon>
                  <Plus />
                </el-icon>
                <template #tip>
                  <div class="el-upload__tip">
                    支持 jpg/png/gif 格式，单张图片不超过 2MB，最多上传 6 张
                  </div>
                </template>
              </el-upload>
            </el-form-item>

            <el-form-item label="描述信息">
              <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入停车场描述信息" />
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 员工管理标签页 -->
        <el-tab-pane label="员工管理" name="staff" :disabled="!isEdit">
          <div class="staff-management">
            <div class="staff-header">
              <h3>当前员工列表</h3>
              <el-button type="primary" size="small" @click="showAddStaffDialog">
                <el-icon>
                  <Plus />
                </el-icon>
                添加员工
              </el-button>
            </div>

            <div class="staff-list" v-loading="staffLoading">
              <div v-if="staffList.length === 0" class="empty-staff">
                <el-empty description="暂无员工" />
              </div>
              <div v-else class="staff-items">
                <div v-for="staff in staffList" :key="staff.id" class="staff-item">
                  <div class="staff-avatar">
                    <el-avatar :src="staff.avatar_url" :size="40">
                      {{ staff.nickname?.charAt(0) || '员' }}
                    </el-avatar>
                  </div>
                  <div class="staff-info">
                    <div class="staff-name">{{ staff.nickname || '未知' }}</div>
                    <div class="staff-phone">{{ staff.phone_number || '无手机号' }}</div>
                    <div class="staff-email">
                      <span class="email-label">邮箱：</span>
                      <span v-if="!staff.editingEmail" class="email-value">
                        {{ staff.email || '未设置' }}
                      </span>
                      <el-input v-else v-model="staff.tempEmail" size="small" placeholder="请输入邮箱地址"
                        style="width: 200px; margin-right: 8px;" @keyup.enter="saveStaffEmail(staff)" />
                    </div>
                  </div>
                  <div class="staff-actions">
                    <el-button v-if="!staff.editingEmail" type="primary" size="small" @click="editStaffEmail(staff)">
                      编辑邮箱
                    </el-button>
                    <el-button v-else type="success" size="small" @click="saveStaffEmail(staff)"
                      :loading="staff.savingEmail">
                      保存
                    </el-button>
                    <el-button v-if="staff.editingEmail" size="small" @click="cancelEditEmail(staff)">
                      取消
                    </el-button>
                    <el-button type="danger" size="small" @click="removeStaff(staff)">
                      移除
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
            {{ submitLoading ? '提交中...' : '确定' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加员工对话框 -->
    <el-dialog v-model="addStaffDialogVisible" title="添加员工" width="500px" :close-on-click-modal="false">
      <div class="add-staff-content">
        <el-input v-model="staffSearchKeyword" placeholder="请输入用户昵称或手机号搜索" @input="handleStaffSearch" clearable>
          <template #prefix>
            <el-icon>
              <Search />
            </el-icon>
          </template>
        </el-input>

        <div class="search-results" v-loading="staffSearchLoading">
          <div v-if="staffSearchResults.length === 0 && staffSearchKeyword" class="no-results">
            <el-empty description="未找到匹配的用户" />
          </div>
          <div v-else-if="staffSearchResults.length > 0" class="user-list">
            <div v-for="user in staffSearchResults" :key="user.id" class="user-item" @click="selectUser(user)">
              <div class="user-avatar">
                <el-avatar :src="user.avatar_url" :size="32">
                  {{ user.nickname?.charAt(0) || '用' }}
                </el-avatar>
              </div>
              <div class="user-info">
                <div class="user-name">{{ user.nickname || '未知' }}</div>
                <div class="user-phone">{{ user.phone_number || '无手机号' }}</div>
              </div>
              <div class="user-action">
                <el-button type="primary" size="small">选择</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addStaffDialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 回复评价对话框 -->
    <el-dialog v-model="replyDialogVisible" title="回复评价" width="600px" :close-on-click-modal="false">
      <div v-if="currentReview" class="reply-dialog-content">
        <div class="original-review">
          <h4>原评价内容</h4>
          <div class="review-summary">
            <div class="review-user">
              <el-avatar :src="currentReview.user_avatar" :size="24">
                {{ currentReview.user_nickname?.charAt(0) || '用' }}
              </el-avatar>
              <span>{{ currentReview.user_nickname || '匿名用户' }}</span>
              <el-rate v-model="currentReview.rating" disabled size="small" />
            </div>
            <p class="review-text">{{ currentReview.comment || '用户未留言' }}</p>
          </div>
        </div>

        <div class="reply-form">
          <h4>回复内容</h4>
          <el-input v-model="replyContent" type="textarea" :rows="4" placeholder="请输入回复内容..." maxlength="500"
            show-word-limit />
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="replyDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="replySubmitting" @click="submitReply">
            {{ replySubmitting ? '提交中...' : '发送回复' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 独立的评价管理对话框 -->
    <el-dialog v-model="reviewsDialogVisible" :title="`${currentParkingLotName} - 评价管理`" width="1000px"
      :close-on-click-modal="false">
      <div class="reviews-management">
        <div class="reviews-header">
          <h3>用户评价列表</h3>
          <div class="reviews-filters">
            <el-select v-model="reviewsFilter.status" placeholder="选择状态" style="width: 120px" @change="loadReviewsList">
              <el-option label="全部" value="" />
              <el-option label="显示" value="visible" />
              <el-option label="隐藏" value="hidden" />
            </el-select>
          </div>
        </div>

        <div class="reviews-list" v-loading="reviewsLoading">
          <div v-if="reviewsList.length === 0" class="empty-reviews">
            <el-empty description="暂无评价" />
          </div>
          <div v-else class="reviews-items">
            <div v-for="review in reviewsList" :key="review.id" class="review-item">
              <div class="review-header">
                <div class="user-info">
                  <el-avatar :src="review.user_avatar" :size="32">
                    {{ review.user_nickname?.charAt(0) || '用' }}
                  </el-avatar>
                  <div class="user-details">
                    <div class="user-name">{{ review.user_nickname || '匿名用户' }}</div>
                    <div class="review-time">{{ formatDate(review.created_at) }}</div>
                  </div>
                </div>
                <div class="review-rating">
                  <el-rate v-model="review.rating" disabled show-score />
                </div>
                <div class="review-actions">
                  <el-button :type="review.status === 'visible' ? 'warning' : 'success'" size="small"
                    @click="toggleReviewStatus(review)">
                    {{ review.status === 'visible' ? '隐藏' : '显示' }}
                  </el-button>
                  <el-button type="primary" size="small" @click="showReplyDialog(review)">
                    回复
                  </el-button>
                </div>
              </div>

              <div class="review-content">
                <p>{{ review.comment || '用户未留言' }}</p>
              </div>

              <div class="review-meta">
                <span class="order-info">订单号：{{ review.order_number }}</span>
                <span class="status-badge" :class="review.status">
                  {{ review.status === 'visible' ? '显示中' : '已隐藏' }}
                </span>
              </div>

              <!-- 回复列表 -->
              <div v-if="review.replies && review.replies.length > 0" class="replies-section">
                <div v-for="reply in review.replies" :key="reply.id" class="reply-item">
                  <div class="reply-header">
                    <span class="reply-author">{{ reply.reply_user_nickname || '管理员' }}</span>
                    <span class="reply-time">{{ formatDate(reply.created_at) }}</span>
                  </div>
                  <div class="reply-content">{{ reply.content }}</div>
                </div>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <div v-if="reviewsList.length > 0" class="reviews-pagination">
            <el-pagination v-model:current-page="reviewsPagination.page" v-model:page-size="reviewsPagination.pageSize"
              :page-sizes="[10, 20, 50]" :total="reviewsPagination.total" layout="total, sizes, prev, pager, next"
              @size-change="handleReviewsSizeChange" @current-change="handleReviewsCurrentChange" />
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="reviewsDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加评论对话框 -->
    <el-dialog
      v-model="addReviewDialogVisible"
      title="添加客户评论"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="addReviewFormRef"
        :model="addReviewForm"
        :rules="addReviewRules"
        label-width="100px"
      >
        <el-form-item label="用户昵称" prop="user_nickname">
          <el-input
            v-model="addReviewForm.user_nickname"
            placeholder="请输入用户昵称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="用户头像" prop="user_avatar">
          <el-input
            v-model="addReviewForm.user_avatar"
            placeholder="请输入用户头像URL（可选）"
          />
          <div class="field-tip">可以留空，系统会使用默认头像</div>
        </el-form-item>

        <el-form-item label="评分" prop="rating">
          <el-rate
            v-model="addReviewForm.rating"
            :max="5"
            show-text
            :texts="['极差', '失望', '一般', '满意', '惊喜']"
          />
        </el-form-item>

        <el-form-item label="评论内容" prop="comment">
          <el-input
            v-model="addReviewForm.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入评论内容"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="评论时间" prop="created_at">
          <el-date-picker
            v-model="addReviewForm.created_at"
            type="datetime"
            placeholder="选择评论时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
          <div class="field-tip">不选择则使用当前时间</div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addReviewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitAddReview" :loading="addReviewLoading">
            确定添加
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete, Refresh, ChatDotRound } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import {
  getParkingLots,
  getParkingLotById,
  createParkingLot,
  updateParkingLot,
  deleteParkingLot,
  getParkingLotCategories,
  getParkingLotReviews,
  updateReviewStatus,
  replyToReview,
  addParkingLotReview,
  type ParkingLot,
  type ParkingLotCategory,
  type CreateParkingLotParams,
  type UpdateParkingLotParams,
  type Review,
  type AddReviewParams
} from '@/api/parkingLot'
import {
  searchUsers,
  getParkingLotManagers,
  addParkingLotManager,
  removeParkingLotManager,
  updateParkingLotManagerEmail,
  type User,
  type ParkingLotManager
} from '@/api/permission'
import { API_CONFIG } from '@/config'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const tableData = ref<ParkingLot[]>([])
const categories = ref<ParkingLotCategory[]>([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentEditId = ref<number | null>(null)
const activeTab = ref('basic')

// 价格配置相关数据
const pricingConfig = reactive({
  type: 'cumulative_daily', // 'cumulative_daily' | 'rolling_24h'
  indoor_outdoor_enabled: false,
  // 统一定价配置（当未启用室内外分别定价时使用）
  daily_prices: {
    day_1: 0.00,
    day_2: 60.00,
    day_3: 80.00,
    day_4: 100.00,
    day_5: 120.00,
    day_6: 140.00,
    day_7: 140.00
  } as Record<string, number>,
  daily_price_after_7: 20.00,
  // 室内价格配置
  indoor_prices: {
    daily_prices: {
      day_1: 0.00,
      day_2: 60.00,
      day_3: 80.00,
      day_4: 100.00,
      day_5: 120.00,
      day_6: 140.00,
      day_7: 140.00
    } as Record<string, number>,
    daily_price_after_7: 20.00
  },
  // 室外价格配置
  outdoor_prices: {
    daily_prices: {
      day_1: 0.00,
      day_2: 50.00,
      day_3: 70.00,
      day_4: 90.00,
      day_5: 110.00,
      day_6: 130.00,
      day_7: 130.00
    } as Record<string, number>,
    daily_price_after_7: 18.00
  },
  description: '累计天数收费模式'
})

// 服务设施数据
const serviceFacilitiesList = ref<string[]>([])

// 图片上传相关数据
const imageFileList = ref<any[]>([])
const uploadHeaders = ref({
  'Authorization': `Bearer ${localStorage.getItem('admin_token') || ''}`
})

// 员工管理相关
const staffLoading = ref(false)
const staffList = ref<ParkingLotManager[]>([])
const addStaffDialogVisible = ref(false)
const staffSearchKeyword = ref('')
const staffSearchLoading = ref(false)
const staffSearchResults = ref<User[]>([])
let staffSearchTimer: number | null = null

// 营业资料上传相关数据
const businessLicenseFileList = ref<any[]>([])
const legalIdFileList = ref<any[]>([])
const leaseContractFileList = ref<any[]>([])
const businessDocuments = reactive<Record<string, any>>({})

// 评价管理相关数据
const reviewsLoading = ref(false)
const reviewsList = ref<Review[]>([])
const reviewsFilter = reactive({
  status: ''
})
const reviewsPagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})
const replyDialogVisible = ref(false)
const currentReview = ref<Review | null>(null)
const replyContent = ref('')
const replySubmitting = ref(false)

// 独立评价管理对话框
const reviewsDialogVisible = ref(false)
const currentParkingLotName = ref('')
const currentReviewsParkingLotId = ref<number | null>(null)

// 添加评论相关数据
const addReviewDialogVisible = ref(false)
const addReviewLoading = ref(false)
const addReviewFormRef = ref<FormInstance>()
const currentAddReviewParkingLot = ref<ParkingLot | null>(null)
const addReviewForm = reactive({
  user_nickname: '',
  user_avatar: '',
  rating: 5,
  comment: '',
  created_at: ''
})

// 添加评论表单验证规则
const addReviewRules: FormRules = {
  user_nickname: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    { min: 1, max: 50, message: '昵称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  rating: [
    { required: true, message: '请选择评分', trigger: 'change' },
    { type: 'number', min: 1, max: 5, message: '评分必须在1-5之间', trigger: 'change' }
  ],
  comment: [
    { required: true, message: '请输入评论内容', trigger: 'blur' },
    { min: 5, max: 500, message: '评论内容长度在 5 到 500 个字符', trigger: 'blur' }
  ]
}

// 搜索表单
const searchForm = reactive({
  name: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 表单引用和数据
const formRef = ref<FormInstance>()
const formData = reactive<CreateParkingLotParams & UpdateParkingLotParams>({
  name: '',
  category_id: undefined,
  address: '',
  total_spaces: 0,
  monthly_sales: 0,
  rating: 0,
  airport_distance_km: undefined,
  station_distance_km: undefined,
  shuttle_time_minutes: undefined,
  contact_phone: '',
  backup_phone: '',
  business_documents: {},
  description: '',
  status: 'pending_review'
})

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入停车场名称', trigger: 'blur' },
    { min: 2, max: 100, message: '名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 255, message: '地址长度在 5 到 255 个字符', trigger: 'blur' }
  ],
  total_spaces: [
    { required: true, message: '请输入车位总数', trigger: 'blur' },
    { type: 'number', min: 1, message: '车位总数必须大于0', trigger: 'change' }
  ],
  monthly_sales: [
    { type: 'number', min: 0, message: '月销量不能为负数', trigger: 'change' }
  ],
  rating: [
    { type: 'number', min: 0, max: 5, message: '评分必须在0-5之间', trigger: 'change' }
  ],
  airport_distance_km: [
    { type: 'number', min: 0, message: '距离不能为负数', trigger: 'change' }
  ],
  station_distance_km: [
    { type: 'number', min: 0, message: '距离不能为负数', trigger: 'change' }
  ],
  shuttle_time_minutes: [
    { type: 'number', min: 0, message: '时间不能为负数', trigger: 'change' }
  ]
}

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑停车场' : '新增停车场')

// 方法定义
/**
 * 获取状态标签类型
 */
function getStatusTagType(status: string): string {
  const typeMap: Record<string, string> = {
    'pending_review': 'warning',
    'approved': 'success',
    'rejected': 'danger',
    'inactive': 'info'
  }
  return typeMap[status] || 'info'
}

/**
 * 获取状态文本
 */
function getStatusText(status: string): string {
  const textMap: Record<string, string> = {
    'pending_review': '待审核',
    'approved': '已通过',
    'rejected': '已拒绝',
    'inactive': '已停用'
  }
  return textMap[status] || '未知'
}

/**
 * 格式化日期
 */
function formatDate(dateString: string): string {
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    return '格式错误'
  }
}

/**
 * 加载停车场列表
 */
async function loadParkingLots() {
  try {
    loading.value = true

    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      name: searchForm.name.trim() || undefined,
      status: searchForm.status || undefined
    }

    const response = await getParkingLots(params)

    if (response.success) {
      tableData.value = response.data.list
      pagination.total = response.data.total
    }
  } catch (error) {
    console.error('加载停车场列表失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

/**
 * 加载停车场分类
 */
async function loadCategories() {
  try {
    const response = await getParkingLotCategories()
    if (response.success) {
      categories.value = response.data
    }
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

/**
 * 搜索处理
 */
function handleSearch() {
  pagination.page = 1
  loadParkingLots()
}

/**
 * 分页大小改变
 */
function handleSizeChange(size: number) {
  pagination.pageSize = size
  pagination.page = 1
  loadParkingLots()
}

/**
 * 当前页改变
 */
function handleCurrentChange(page: number) {
  pagination.page = page
  loadParkingLots()
}

/**
 * 排序改变
 */
function handleSortChange() {
  // 这里可以实现排序逻辑
  loadParkingLots()
}

/**
 * 新增停车场
 */
function handleAdd() {
  isEdit.value = false
  currentEditId.value = null
  resetForm()

  // 重置价格配置为默认值
  resetToDefaultPricing()

  dialogVisible.value = true
}

/**
 * 查看停车场评价
 */
async function handleViewReviews(row: ParkingLot) {
  currentReviewsParkingLotId.value = row.id
  currentParkingLotName.value = row.name
  reviewsDialogVisible.value = true

  // 重置分页
  reviewsPagination.page = 1
  reviewsFilter.status = ''

  // 加载评价列表
  await loadReviewsList()
}

/**
 * 编辑停车场
 */
async function handleEdit(row: ParkingLot) {
  try {
    // 首先重置所有数据
    resetForm()
    
    isEdit.value = true
    currentEditId.value = row.id
    activeTab.value = 'basic'

    // 获取详细信息
    const response = await getParkingLotById(row.id)
    if (response.success) {
      const data = response.data
      Object.assign(formData, {
        name: data.name,
        category_id: data.category_id,
        address: data.address,
        total_spaces: Number(data.total_spaces) || 0,
        monthly_sales: Number(data.monthly_sales) || 0,
        rating: Number(data.rating) || 0,
        airport_distance_km: Number(data.airport_distance_km) || null,
        station_distance_km: Number(data.station_distance_km) || null,
        shuttle_time_minutes: Number(data.shuttle_time_minutes) || null,
        contact_phone: data.contact_phone,
        backup_phone: data.backup_phone,
        business_documents: data.business_documents || {},
        description: data.description,
        status: data.status
      })

      // 处理价格规则数据
      if (data.price_rules && typeof data.price_rules === 'object') {
        if (data.price_rules.indoor_outdoor_enabled && data.price_rules.indoor_prices && data.price_rules.outdoor_prices) {
          // 室内外分别定价模式
          console.log('加载室内外分别定价模式数据:', data.price_rules)
          Object.assign(pricingConfig, {
            type: data.price_rules.type || 'cumulative_daily',
            indoor_outdoor_enabled: true,
            indoor_prices: data.price_rules.indoor_prices,
            outdoor_prices: data.price_rules.outdoor_prices,
            description: data.price_rules.description || '室内外分别定价模式'
          })
        } else if (data.price_rules.type === 'cumulative_daily' && data.price_rules.daily_prices) {
          // 统一定价模式 - 自然天计费
          console.log('加载统一定价模式数据:', data.price_rules)
          console.log('当前pricingConfig状态:', pricingConfig)
          Object.assign(pricingConfig, {
            type: data.price_rules.type,
            indoor_outdoor_enabled: false,
            daily_prices: data.price_rules.daily_prices,
            daily_price_after_7: data.price_rules.daily_price_after_7 || 20.00,
            description: data.price_rules.description || '累计天数收费模式'
          })
          console.log('更新后pricingConfig状态:', pricingConfig)
        } else if (data.price_rules.type === 'rolling_24h' && data.price_rules.daily_prices) {
          // 24小时计费模式
          console.log('加载24小时计费模式数据:', data.price_rules)
          Object.assign(pricingConfig, {
            type: data.price_rules.type,
            indoor_outdoor_enabled: data.price_rules.indoor_outdoor_enabled || false,
            daily_prices: data.price_rules.daily_prices,
            daily_price_after_7: data.price_rules.daily_price_after_7 || 20.00,
            description: data.price_rules.description || '24小时计费模式'
          })
          
          // 如果是室内外分别定价模式，也要加载对应数据
          if (data.price_rules.indoor_outdoor_enabled) {
            if (data.price_rules.indoor_prices) {
              Object.assign(pricingConfig.indoor_prices, data.price_rules.indoor_prices)
            }
            if (data.price_rules.outdoor_prices) {
              Object.assign(pricingConfig.outdoor_prices, data.price_rules.outdoor_prices)
            }
          }
          console.log('24小时计费模式加载完成:', pricingConfig)
        } else {
          // 使用默认配置
          resetToDefaultPricing()
        }
      } else {
        // 使用默认配置
        resetToDefaultPricing()
      }

      // 处理服务设施数据
      if (data.service_facilities && Array.isArray(data.service_facilities)) {
        serviceFacilitiesList.value = data.service_facilities
      } else {
        serviceFacilitiesList.value = []
      }

      // 处理图片数据
      if (data.image_urls && Array.isArray(data.image_urls)) {
        imageFileList.value = data.image_urls.map((url: string, index: number) => ({
          uid: `image_${Date.now()}_${index}`,
          name: `image_${index + 1}.jpg`,
          status: 'done',
          url: url.startsWith('/uploads/') ? `${API_CONFIG.SERVER_URL}${url}` : url,
          originalUrl: url // 保存原始相对路径
        }))
      } else {
        imageFileList.value = []
      }

      // 处理营业资料数据
      if (data.business_documents && typeof data.business_documents === 'object') {
        Object.assign(businessDocuments, data.business_documents)

        // 处理营业执照
        if (businessDocuments.business_license) {
          // 兼容数组和对象格式
          const businessLicenseData = Array.isArray(businessDocuments.business_license) 
            ? businessDocuments.business_license[0] 
            : businessDocuments.business_license
          
          if (businessLicenseData && businessLicenseData.url) {
            businessLicenseFileList.value = [{
              uid: `business_license_${Date.now()}`,
              name: businessLicenseData.filename || 'business_license.jpg',
              status: 'done',
              url: businessLicenseData.url.startsWith('/uploads/')
                ? `${API_CONFIG.SERVER_URL}${businessLicenseData.url}`
                : businessLicenseData.url
            }]
          } else {
            businessLicenseFileList.value = []
          }
        } else {
          businessLicenseFileList.value = []
        }

        // 处理法人身份证
        if (businessDocuments.legal_id) {
          // 兼容数组和对象格式
          const legalIdData = Array.isArray(businessDocuments.legal_id) 
            ? businessDocuments.legal_id[0] 
            : businessDocuments.legal_id
          
          if (legalIdData && legalIdData.url) {
            legalIdFileList.value = [{
              uid: `legal_id_${Date.now()}`,
              name: legalIdData.filename || 'legal_id.jpg',
              status: 'done',
              url: legalIdData.url.startsWith('/uploads/')
                ? `${API_CONFIG.SERVER_URL}${legalIdData.url}`
                : legalIdData.url
            }]
          } else {
            legalIdFileList.value = []
          }
        } else {
          legalIdFileList.value = []
        }

        // 处理租赁合同
        if (businessDocuments.lease_contract) {
          // 兼容数组和对象格式
          const leaseContractData = Array.isArray(businessDocuments.lease_contract) 
            ? businessDocuments.lease_contract[0] 
            : businessDocuments.lease_contract
          
          if (leaseContractData && leaseContractData.url) {
            leaseContractFileList.value = [{
              uid: `lease_contract_${Date.now()}`,
              name: leaseContractData.filename || 'lease_contract.pdf',
              status: 'done',
              url: leaseContractData.url.startsWith('/uploads/')
                ? `${API_CONFIG.SERVER_URL}${leaseContractData.url}`
                : leaseContractData.url
            }]
          } else {
            leaseContractFileList.value = []
          }
        } else {
          leaseContractFileList.value = []
        }
      } else {
        businessLicenseFileList.value = []
        legalIdFileList.value = []
        leaseContractFileList.value = []
        Object.assign(businessDocuments, {})
      }

      // 加载员工列表
      await loadStaffList()

      dialogVisible.value = true

      // 清除表单验证状态
      nextTick(() => {
        formRef.value?.clearValidate()
      })
    }
  } catch (error) {
    console.error('获取停车场详情失败:', error)
    ElMessage.error('获取数据失败')
  }
}

/**
 * 配置价格
 */
function handleConfigPricing(row: ParkingLot) {
  // 跳转到价格配置页面
  window.open(`/parking-lots/pricing?id=${row.id}&name=${encodeURIComponent(row.name)}`, '_blank')
}

/**
 * 删除停车场
 */
async function handleDelete(row: ParkingLot) {
  try {
    await ElMessageBox.confirm(
      `确定要删除停车场"${row.name}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await deleteParkingLot(row.id)
    if (response.success) {
      ElMessage.success('删除成功')
      loadParkingLots()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

/**
 * 提交表单
 */
async function handleSubmit() {
  if (!formRef.value) return

  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    submitLoading.value = true

    // 准备提交数据
    const submitData = {
      ...formData,
      price_rules: pricingConfig,
      service_facilities: serviceFacilitiesList.value,
      image_urls: imageFileList.value
        .filter(file => file.url && file.status === 'done')
        .map(file => {
          // 优先使用原始相对路径
          if (file.originalUrl) {
            return file.originalUrl
          }
          // 如果是完整URL，提取相对路径
          if (file.url.startsWith(API_CONFIG.SERVER_URL)) {
            return file.url.replace(API_CONFIG.SERVER_URL, '')
          }
          return file.url
        })
    }

    if (isEdit.value && currentEditId.value) {
      // 更新
      const response = await updateParkingLot(currentEditId.value, submitData)
      if (response.success) {
        ElMessage.success('更新成功')
        dialogVisible.value = false
        loadParkingLots()
      } else {
        ElMessage.error(response.message || '更新失败')
      }
    } else {
      // 创建
      const response = await createParkingLot(submitData)
      if (response.success) {
        ElMessage.success('创建成功')
        dialogVisible.value = false
        loadParkingLots()
      } else {
        ElMessage.error(response.message || '创建失败')
      }
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

/**
 * 重置表单
 */
function resetForm() {
  Object.assign(formData, {
    name: '',
    category_id: undefined,
    address: '',
    total_spaces: 0,
    monthly_sales: 0,
    rating: 0,
    airport_distance_km: undefined,
    station_distance_km: undefined,
    shuttle_time_minutes: undefined,
    contact_phone: '',
    backup_phone: '',
    business_documents: {},
    description: '',
    status: 'pending_review'
  })

  // 重置价格配置
  resetToDefaultPricing()

  // 重置服务设施
  serviceFacilitiesList.value = []

  // 重置图片列表
  imageFileList.value = []

  // 重置营业资料
  businessLicenseFileList.value = []
  legalIdFileList.value = []
  leaseContractFileList.value = []
  
  // 清空 businessDocuments 对象的所有属性
  Object.keys(businessDocuments).forEach(key => {
    delete businessDocuments[key]
  })

  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// ==================== 价格配置相关方法 ====================

/**
 * 重置为默认价格配置
 */
function resetToDefaultPricing() {
  Object.assign(pricingConfig, {
    type: 'cumulative_daily',
    indoor_outdoor_enabled: false,
    daily_prices: {
      day_1: 0.00,
      day_2: 60.00,
      day_3: 80.00,
      day_4: 100.00,
      day_5: 120.00,
      day_6: 140.00,
      day_7: 140.00
    },
    daily_price_after_7: 20.00,
    indoor_prices: {
      daily_prices: {
        day_1: 0.00,
        day_2: 60.00,
        day_3: 80.00,
        day_4: 100.00,
        day_5: 120.00,
        day_6: 140.00,
        day_7: 140.00
      },
      daily_price_after_7: 20.00
    },
    outdoor_prices: {
      daily_prices: {
        day_1: 0.00,
        day_2: 50.00,
        day_3: 70.00,
        day_4: 90.00,
        day_5: 110.00,
        day_6: 130.00,
        day_7: 130.00
      },
      daily_price_after_7: 18.00
    },
    description: '累计天数收费模式'
  })
}

/**
 * 获取价格预览（统一定价模式）
 */
function getPreviewPrice(day: number): number {
  if (day <= 7) {
    const dayKey = `day_${day}` as keyof typeof pricingConfig.daily_prices
    return pricingConfig.daily_prices[dayKey] || 0
  } else {
    // 超过7天的计算：第7天价格 + (超出天数 * 每日价格)
    const day7Price = pricingConfig.daily_prices.day_7 || 0
    const extraDays = day - 7
    const extraPrice = extraDays * (pricingConfig.daily_price_after_7 || 0)
    return day7Price + extraPrice
  }
}

/**
 * 获取室内价格预览
 */
function getIndoorPreviewPrice(day: number): number {
  if (day <= 7) {
    const dayKey = `day_${day}` as keyof typeof pricingConfig.indoor_prices.daily_prices
    return pricingConfig.indoor_prices.daily_prices[dayKey] || 0
  } else {
    // 超过7天的计算：第7天价格 + (超出天数 * 每日价格)
    const day7Price = pricingConfig.indoor_prices.daily_prices.day_7 || 0
    const extraDays = day - 7
    const extraPrice = extraDays * (pricingConfig.indoor_prices.daily_price_after_7 || 0)
    return day7Price + extraPrice
  }
}

/**
 * 获取室外价格预览
 */
function getOutdoorPreviewPrice(day: number): number {
  if (day <= 7) {
    const dayKey = `day_${day}` as keyof typeof pricingConfig.outdoor_prices.daily_prices
    return pricingConfig.outdoor_prices.daily_prices[dayKey] || 0
  } else {
    // 超过7天的计算：第7天价格 + (超出天数 * 每日价格)
    const day7Price = pricingConfig.outdoor_prices.daily_prices.day_7 || 0
    const extraDays = day - 7
    const extraPrice = extraDays * (pricingConfig.outdoor_prices.daily_price_after_7 || 0)
    return day7Price + extraPrice
  }
}

/**
 * 室内外定价开关切换处理
 */
function onIndoorOutdoorToggle(enabled: boolean) {
  if (enabled) {
    // 启用室内外分别定价时，将当前统一价格复制到室内价格
    Object.assign(pricingConfig.indoor_prices, {
      daily_prices: { ...pricingConfig.daily_prices },
      daily_price_after_7: pricingConfig.daily_price_after_7
    })

    // 设置默认的室外价格（比室内价格稍低）
    Object.assign(pricingConfig.outdoor_prices, {
      daily_prices: {
        day_1: 0.00,
        day_2: Math.max(0, (pricingConfig.daily_prices.day_2 || 60) - 10),
        day_3: Math.max(0, (pricingConfig.daily_prices.day_3 || 80) - 10),
        day_4: Math.max(0, (pricingConfig.daily_prices.day_4 || 100) - 10),
        day_5: Math.max(0, (pricingConfig.daily_prices.day_5 || 120) - 10),
        day_6: Math.max(0, (pricingConfig.daily_prices.day_6 || 140) - 10),
        day_7: Math.max(0, (pricingConfig.daily_prices.day_7 || 140) - 10)
      },
      daily_price_after_7: Math.max(0, (pricingConfig.daily_price_after_7 || 20) - 2)
    })

    pricingConfig.description = '室内外分别定价模式'
  } else {
    pricingConfig.description = '累计天数收费模式'
  }
}

// ==================== 图片上传相关方法 ====================

/**
 * 图片上传前的检查
 */
function beforeImageUpload(file: File) {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

/**
 * 图片上传成功回调
 */
function handleImageUploadSuccess(response: any, file: any) {
  if (response.success && response.data?.url) {
    // 更新文件列表中的 URL 和状态
    const fileIndex = imageFileList.value.findIndex(item => item.uid === file.uid)
    if (fileIndex !== -1) {
      // 显示时使用完整URL，便于预览
      imageFileList.value[fileIndex].url = `${API_CONFIG.SERVER_URL}${response.data.url}`
      imageFileList.value[fileIndex].status = 'done'
      // 存储原始相对路径用于提交
      imageFileList.value[fileIndex].originalUrl = response.data.url
    }
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(response.message || '图片上传失败')
  }
}

/**
 * 图片上传失败回调
 */
function handleImageUploadError(error: any) {
  console.error('图片上传失败:', error)
  ElMessage.error('图片上传失败，请重试')
}

/**
 * 图片删除回调
 */
function handleImageRemove(file: any) {
  const index = imageFileList.value.findIndex(item => item.uid === file.uid)
  if (index !== -1) {
    imageFileList.value.splice(index, 1)
  }
}

/**
 * 对话框关闭处理
 */
function handleDialogClose() {
  resetForm()
  staffList.value = []
  activeTab.value = 'basic'
}

// ==================== 员工管理相关方法 ====================

/**
 * 加载员工列表
 */
async function loadStaffList() {
  if (!currentEditId.value) return

  try {
    staffLoading.value = true
    const response = await getParkingLotManagers(currentEditId.value)
    if (response.success) {
      // 初始化编辑状态属性，确保响应式
      staffList.value = response.data.map((staff: ParkingLotManager) => ({
        ...staff,
        editingEmail: false,
        tempEmail: '',
        savingEmail: false
      }))
      console.log('✅ 员工列表加载完成，已初始化编辑状态', staffList.value)
    }
  } catch (error) {
    console.error('加载员工列表失败:', error)
    ElMessage.error('加载员工列表失败')
  } finally {
    staffLoading.value = false
  }
}

/**
 * 显示添加员工对话框
 */
function showAddStaffDialog() {
  addStaffDialogVisible.value = true
  staffSearchKeyword.value = ''
  staffSearchResults.value = []
}

/**
 * 员工搜索处理（防抖）
 */
function handleStaffSearch() {
  if (staffSearchTimer) {
    clearTimeout(staffSearchTimer)
  }

  staffSearchTimer = setTimeout(() => {
    if (staffSearchKeyword.value.trim()) {
      performStaffSearch()
    } else {
      staffSearchResults.value = []
    }
  }, 500)
}

/**
 * 执行员工搜索
 */
async function performStaffSearch() {
  try {
    staffSearchLoading.value = true
    const response = await searchUsers(staffSearchKeyword.value.trim())
    if (response.success) {
      staffSearchResults.value = response.data
    }
  } catch (error) {
    console.error('搜索用户失败:', error)
    ElMessage.error('搜索失败')
  } finally {
    staffSearchLoading.value = false
  }
}

/**
 * 选择用户作为员工
 */
async function selectUser(user: User) {
  if (!currentEditId.value) return

  try {
    const response = await addParkingLotManager(currentEditId.value, user.id)
    if (response.success) {
      ElMessage.success('添加员工成功')
      addStaffDialogVisible.value = false
      await loadStaffList()
    } else {
      ElMessage.error(response.message || '添加员工失败')
    }
  } catch (error) {
    console.error('添加员工失败:', error)
    ElMessage.error('添加员工失败')
  }
}

/**
 * 移除员工
 */
async function removeStaff(staff: ParkingLotManager) {
  if (!currentEditId.value) return

  try {
    await ElMessageBox.confirm(
      `确定要移除员工"${staff.nickname}"吗？`,
      '确认移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await removeParkingLotManager(currentEditId.value, staff.id)
    if (response.success) {
      ElMessage.success('移除员工成功')
      await loadStaffList()
    } else {
      ElMessage.error(response.message || '移除员工失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('移除员工失败:', error)
      ElMessage.error('移除员工失败')
    }
  }
}

/**
 * 编辑员工邮箱
 */
function editStaffEmail(staff: ParkingLotManager) {
  console.log('🔧 editStaffEmail 被调用', staff)
  // 使用 Vue 的响应式方式设置属性
  Object.assign(staff, {
    editingEmail: true,
    tempEmail: staff.email || '',
    savingEmail: false
  })
  console.log('✅ 编辑状态已设置', { editingEmail: staff.editingEmail, tempEmail: staff.tempEmail })
}

/**
 * 取消编辑邮箱
 */
function cancelEditEmail(staff: ParkingLotManager) {
  console.log('🔧 cancelEditEmail 被调用', staff)
  Object.assign(staff, {
    editingEmail: false,
    tempEmail: '',
    savingEmail: false
  })
  console.log('✅ 编辑状态已取消')
}

/**
 * 保存员工邮箱
 */
async function saveStaffEmail(staff: ParkingLotManager) {
  console.log('🔧 saveStaffEmail 被调用', {
    currentEditId: currentEditId.value,
    staffId: staff.id,
    tempEmail: staff.tempEmail
  })

  if (!currentEditId.value) {
    console.log('❌ currentEditId 为空')
    return
  }

  // 验证邮箱格式
  if (staff.tempEmail && staff.tempEmail.trim()) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailRegex.test(staff.tempEmail.trim())) {
      console.log('❌ 邮箱格式无效:', staff.tempEmail)
      ElMessage.error('邮箱格式无效')
      return
    }
  }

  try {
    console.log('📤 准备发送API请求:', {
      parkingLotId: currentEditId.value,
      userId: staff.id,
      email: staff.tempEmail?.trim() || ''
    })

    staff.savingEmail = true
    const response = await updateParkingLotManagerEmail(
      currentEditId.value,
      staff.id,
      staff.tempEmail?.trim() || ''
    )

    console.log('📥 API响应:', response)

    if (response.success) {
      // 更新本地状态
      Object.assign(staff, {
        email: staff.tempEmail?.trim() || '',
        editingEmail: false,
        tempEmail: '',
        savingEmail: false
      })
      console.log('✅ 邮箱更新成功，本地状态已更新', { email: staff.email })
      ElMessage.success('邮箱更新成功')
    } else {
      console.log('❌ API返回失败:', response.message)
      ElMessage.error(response.message || '邮箱更新失败')
    }
  } catch (error) {
    console.error('❌ 更新邮箱异常:', error)
    ElMessage.error('邮箱更新失败')
  } finally {
    staff.savingEmail = false
  }
}

// ==================== 营业资料上传相关方法 ====================

/**
 * 营业资料上传前的检查
 */
function beforeBusinessDocumentUpload(file: File) {
  const isValidType = file.type.startsWith('image/') || file.type === 'application/pdf'
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isValidType) {
    ElMessage.error('只能上传图片或PDF文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('文件大小不能超过 5MB!')
    return false
  }
  return true
}

/**
 * 营业资料上传成功回调
 */
function handleBusinessDocumentUploadSuccess(response: any, file: any, documentType: string) {
  if (response.success && response.data?.url) {
    // 更新businessDocuments对象
    businessDocuments[documentType] = {
      url: response.data.url,
      upload_time: new Date().toISOString(),
      filename: file.name
    }

    // 更新formData中的business_documents
    formData.business_documents = { ...businessDocuments }

    ElMessage.success('文件上传成功')
  } else {
    ElMessage.error(response.message || '文件上传失败')
  }
}

/**
 * 营业资料上传失败回调
 */
function handleBusinessDocumentUploadError(error: any) {
  console.error('文件上传失败:', error)
  ElMessage.error('文件上传失败，请重试')
}

/**
 * 营业资料删除回调
 */
function handleBusinessDocumentRemove(file: any, documentType: string) {
  delete businessDocuments[documentType]
  formData.business_documents = { ...businessDocuments }
}

// ==================== 评价管理相关方法 ====================

/**
 * 加载评价列表
 */
async function loadReviewsList() {
  if (!currentReviewsParkingLotId.value) return

  try {
    reviewsLoading.value = true
    const response = await getParkingLotReviews(currentReviewsParkingLotId.value, {
      page: reviewsPagination.page,
      pageSize: reviewsPagination.pageSize,
      status: reviewsFilter.status || undefined
    })

    if (response.success) {
      reviewsList.value = response.data.list
      reviewsPagination.total = response.data.total
    }
  } catch (error) {
    console.error('加载评价列表失败:', error)
    ElMessage.error('加载评价列表失败')
  } finally {
    reviewsLoading.value = false
  }
}

/**
 * 切换评价状态
 */
async function toggleReviewStatus(review: Review) {
  try {
    const newStatus = review.status === 'visible' ? 'hidden' : 'visible'
    const response = await updateReviewStatus(review.id, newStatus)

    if (response.success) {
      review.status = newStatus
      ElMessage.success(`评价已${newStatus === 'visible' ? '显示' : '隐藏'}`)
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('更新评价状态失败:', error)
    ElMessage.error('操作失败')
  }
}

/**
 * 显示回复对话框
 */
function showReplyDialog(review: Review) {
  currentReview.value = review
  replyContent.value = ''
  replyDialogVisible.value = true
}

/**
 * 提交回复
 */
async function submitReply() {
  if (!currentReview.value || !replyContent.value.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }

  try {
    replySubmitting.value = true
    const response = await replyToReview(currentReview.value.id, replyContent.value.trim())

    if (response.success) {
      ElMessage.success('回复成功')
      replyDialogVisible.value = false
      // 重新加载评价列表以显示新回复
      await loadReviewsList()
    } else {
      ElMessage.error(response.message || '回复失败')
    }
  } catch (error) {
    console.error('回复失败:', error)
    ElMessage.error('回复失败')
  } finally {
    replySubmitting.value = false
  }
}

/**
 * 评价分页大小改变
 */
function handleReviewsSizeChange(size: number) {
  reviewsPagination.pageSize = size
  reviewsPagination.page = 1
  loadReviewsList()
}

/**
 * 评价当前页改变
 */
function handleReviewsCurrentChange(page: number) {
  reviewsPagination.page = page
  loadReviewsList()
}

// ==================== 添加评论相关方法 ====================

/**
 * 显示添加评论对话框
 */
function handleAddReview(row: ParkingLot) {
  currentAddReviewParkingLot.value = row

  // 重置表单
  Object.assign(addReviewForm, {
    user_nickname: '',
    user_avatar: '',
    rating: 5,
    comment: '',
    created_at: ''
  })

  addReviewDialogVisible.value = true

  // 清除表单验证状态
  nextTick(() => {
    addReviewFormRef.value?.clearValidate()
  })
}

/**
 * 提交添加评论
 */
async function handleSubmitAddReview() {
  if (!addReviewFormRef.value || !currentAddReviewParkingLot.value) return

  try {
    // 验证表单
    await addReviewFormRef.value.validate()

    addReviewLoading.value = true

    // 准备提交数据
    const submitData: AddReviewParams = {
      parking_lot_id: currentAddReviewParkingLot.value.id,
      user_nickname: addReviewForm.user_nickname,
      user_avatar: addReviewForm.user_avatar || undefined,
      rating: addReviewForm.rating,
      comment: addReviewForm.comment,
      created_at: addReviewForm.created_at || new Date().toISOString(),
      status: 'approved' // 管理员添加的评论直接审核通过
    }

    // 调用API添加评论
    const result = await addParkingLotReview(submitData)

    if (result.success) {
      ElMessage.success('评论添加成功')
      addReviewDialogVisible.value = false

      // 如果当前正在查看该停车场的评价，刷新评价列表
      if (reviewsDialogVisible.value && currentReviewsParkingLotId.value === currentAddReviewParkingLot.value.id) {
        loadReviewsList()
      }
    } else {
      ElMessage.error(result.message || '添加评论失败')
    }

  } catch (error) {
    console.error('添加评论失败:', error)
    ElMessage.error('添加评论失败')
  } finally {
    addReviewLoading.value = false
  }
}

// 生命周期
onMounted(() => {
  loadParkingLots()
  loadCategories()
})
</script>

<style scoped>
.parking-lot-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-area {
  display: flex;
  align-items: center;
}

.table-card {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.text-gray {
  color: #999;
}

.dialog-footer {
  text-align: right;
}

/* 员工管理样式 */
.staff-management {
  padding: 20px 0;
}

.staff-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.staff-header h3 {
  margin: 0;
  color: #333;
}

.staff-list {
  min-height: 200px;
}

.empty-staff {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.staff-items {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.staff-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fafafa;
}

.staff-avatar {
  margin-right: 12px;
}

.staff-info {
  flex: 1;
}

.staff-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.staff-phone {
  font-size: 12px;
  color: #666;
}

.staff-email {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
  display: flex;
  align-items: center;
}

.email-label {
  margin-right: 4px;
}

.email-value {
  color: #999;
}

.staff-actions {
  margin-left: 12px;
}

/* 添加员工对话框样式 */
.add-staff-content {
  padding: 10px 0;
}

.search-results {
  margin-top: 20px;
  max-height: 300px;
  overflow-y: auto;
}

.no-results {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 150px;
}

.user-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.user-item:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.user-avatar {
  margin-right: 12px;
}

.user-info {
  flex: 1;
}

.user-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.user-phone {
  font-size: 12px;
  color: #666;
}

.user-action {
  margin-left: 12px;
}

/* 价格规则样式 */
.price-rules-container {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  background-color: #fafafa;
}

.price-rules-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.rules-title {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.empty-rules {
  padding: 20px;
  text-align: center;
}

.price-rules-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.price-rule-item {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 16px;
  background-color: white;
}

.rule-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.rule-index {
  font-weight: 500;
  color: #409eff;
  font-size: 14px;
}

/* 服务设施样式 */
.facilities-group {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.facilities-group .el-checkbox {
  margin-right: 0;
}

/* 图片上传样式 */
.el-upload__tip {
  color: #999;
  font-size: 12px;
  margin-top: 8px;
}

/* 价格配置相关样式 */
.price-rules-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;
}

.header-actions {
  display: flex;
  align-items: center;
}

.rules-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.pricing-config {
  background: #fff;
  border-radius: 6px;
  padding: 16px;
}

.unified-pricing {
  /* 统一定价样式 */
}

.indoor-outdoor-pricing {
  /* 室内外分别定价样式 */
}

.indoor-pricing-section,
.outdoor-pricing-section {
  margin-bottom: 32px;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.indoor-pricing-section {
  background: linear-gradient(135deg, #f8f9ff 0%, #f0f2ff 100%);
  border-color: #c6d1f8;
}

.outdoor-pricing-section {
  background: linear-gradient(135deg, #fff8f0 0%, #fff2e6 100%);
  border-color: #f8d1a6;
}

.indoor-outdoor-preview {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
}

.indoor-preview,
.outdoor-preview {
  padding: 16px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.indoor-preview {
  background: linear-gradient(135deg, #f8f9ff 0%, #f0f2ff 100%);
  border-color: #c6d1f8;
}

.outdoor-preview {
  background: linear-gradient(135deg, #fff8f0 0%, #fff2e6 100%);
  border-color: #f8d1a6;
}

.preview-subtitle {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: #606266;
}

.section-title {
  margin: 0 0 16px 0;
  font-size: 14px;
  font-weight: 600;
  color: #606266;
  border-left: 3px solid #409eff;
  padding-left: 8px;
}

.daily-prices-section {
  margin-bottom: 24px;
}

.daily-prices-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.daily-price-item {
  position: relative;
}

.daily-price-item .el-form-item {
  margin-bottom: 0;
}

/* 价格输入框包装器 */
.price-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  width: 100%;
}

/* 模拟Element Plus输入框样式 */
.el-input-style {
  display: inline-block;
  width: 100%;
  height: 32px;
  padding: 0 15px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  color: #606266;
  font-size: 14px;
  line-height: 32px;
  box-sizing: border-box;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  outline: none;
}

.el-input-style:focus {
  border-color: #409eff;
  outline: 0;
}

.el-input-style:hover {
  border-color: #c0c4cc;
}

.el-input-style::placeholder {
  color: #c0c4cc;
}

.el-input-style:disabled {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #c0c4cc;
  cursor: not-allowed;
}

.price-unit {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  color: #909399;
  font-size: 12px;
  pointer-events: none;
}

.after-7-days-section {
  margin-bottom: 24px;
  padding: 16px;
  background: #f0f9ff;
  border-radius: 6px;
  border: 1px solid #b3d8ff;
}

.price-preview-section {
  margin-bottom: 24px;
}

.preview-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 12px;
}

.preview-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.preview-day {
  font-size: 12px;
  color: #6c757d;
  margin-bottom: 4px;
}

.preview-price {
  font-size: 14px;
  font-weight: 600;
  color: #28a745;
}

.pricing-description {
  margin-top: 16px;
}

.pricing-description ul {
  margin: 8px 0 0 0;
  padding-left: 20px;
}

.pricing-description li {
  margin-bottom: 4px;
  font-size: 13px;
  line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .operation-bar {
    flex-direction: column;
    gap: 15px;
  }

  .search-area {
    flex-direction: column;
    gap: 10px;
    width: 100%;
  }

  .search-area .el-input,
  .search-area .el-select {
    width: 100% !important;
  }

  .staff-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }

  .staff-item,
  .user-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .staff-actions,
  .user-action {
    margin-left: 0;
    align-self: flex-end;
  }

  .price-rules-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }

  .facilities-group {
    flex-direction: column;
    gap: 8px;
  }

  .rule-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
}

/* 新字段相关样式 */
.field-tip {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

/* 表格距离信息样式 */
.distance-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
  font-size: 12px;
}

.distance-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.distance-label {
  color: #666;
  font-size: 11px;
}

.distance-value {
  color: #333;
  font-weight: 500;
}

/* 营业资料上传样式 */
.business-documents-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.document-section {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 16px;
  background-color: #fafafa;
}

.document-title {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

/* 评价管理样式 */
.reviews-management {
  padding: 20px 0;
}

.reviews-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.reviews-header h3 {
  margin: 0;
  color: #333;
}

.reviews-filters {
  display: flex;
  gap: 10px;
  align-items: center;
}

.reviews-list {
  min-height: 300px;
}

.empty-reviews {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.reviews-items {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.review-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  background-color: #fff;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.user-name {
  font-weight: 500;
  color: #333;
}

.review-time {
  font-size: 12px;
  color: #999;
}

.review-rating {
  display: flex;
  align-items: center;
}

.review-actions {
  display: flex;
  gap: 8px;
}

.review-content {
  margin: 12px 0;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 6px;
  line-height: 1.5;
}

.review-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #666;
}

.order-info {
  color: #666;
}

.status-badge {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 500;
}

.status-badge.visible {
  background-color: #e7f5e7;
  color: #52c41a;
}

.status-badge.hidden {
  background-color: #fff2e8;
  color: #fa8c16;
}

.replies-section {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.reply-item {
  margin-bottom: 8px;
  padding: 8px 12px;
  background-color: #f0f7ff;
  border-radius: 6px;
  border-left: 3px solid #1890ff;
}

.reply-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.reply-author {
  font-weight: 500;
  color: #1890ff;
  font-size: 12px;
}

.reply-time {
  font-size: 11px;
  color: #999;
}

.reply-content {
  font-size: 13px;
  color: #333;
  line-height: 1.4;
}

.reviews-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 回复对话框样式 */
.reply-dialog-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.original-review h4,
.reply-form h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.review-summary {
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.review-user {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.review-text {
  margin: 0;
  color: #666;
  line-height: 1.5;
}

/* 响应式样式调整 */
@media (max-width: 768px) {
  .business-documents-container {
    gap: 16px;
  }

  .document-section {
    padding: 12px;
  }

  .review-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .review-actions {
    align-self: flex-end;
  }

  .review-meta {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
}

/* 添加评论对话框样式 */
.field-tip {
  font-size: 12px;
  color: #6c757d;
  margin-top: 4px;
  line-height: 1.4;
}
</style>
